package com.gobuy.system.utils;

import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Gaozexi on 2020/6/8 17:18
 * Step by Step  and Stand on,  You Are The Best Investment!
 */
public class IpUtil {
    //获取真实ip
    public static String getIpAddress(ServerHttpRequest request) {
        HttpHeaders headers = request.getHeaders();
        String ip = headers.getFirst("x-forwarded-for");
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            if (ip.indexOf(",") != -1) {
                ip = ip.split(",")[0];
            }
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = headers.getFirst("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = headers.getFirst("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = headers.getFirst("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = headers.getFirst("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = headers.getFirst("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddress().getAddress().getHostAddress();
        }
        return ip;
    }


    //根据域名获得主机的IP地址
    public static String getIPByName(String hostName) {
        try {
            InetAddress addr = InetAddress.getByName(hostName);//根据域名创建主机地址对象
            String hostAddr = addr.getHostAddress();//获取主机IP地址
            return hostAddr;
        } catch (UnknownHostException e) {
            System.out.println("不能根据域名获得主机IP地址：" + e.getMessage());
            return null;
        }
    }

    //根据域名获得主机所有的IP地址
    public  static List<String> getAllIPByName(String hostName) {
        try {
            InetAddress[] addrs = InetAddress.getAllByName(hostName);//根据域名创建主机地址对象
            String[] ips = new String[addrs.length];
            List<String> list = new ArrayList<>();
             for (int i = 0; i < addrs.length; i++) {
                ips[i] = addrs[i].getHostAddress();//获取主机IP地址
                list.add(ips[i]) ;
            }
            return list;
        } catch (UnknownHostException e) {
            System.out.println("不能根据域名获得 主机所有IP地址：" + e.getMessage());
            return null;
        }

    }
}
